package com.seabook.happy.website.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Text;
import com.seabook.happy.website.daos.NewsDao;
import com.seabook.happy.website.pojos.News;

public class NewsUpdateServlet extends HttpServlet {
	private NewsDao newsDao = new NewsDao();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String requestActionParam = req.getParameter("action");
		if ("new".equals(requestActionParam)) {
			createNews(req, resp);
		} else if ("update".equals(requestActionParam)) {
			//TODO
		} else if ("del".equals(requestActionParam)) {
			deleteNews(req, resp);
		} else {
			//TODO
		}
	}

	private boolean deleteNews(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = (String) req.getParameter("news-id");
		newsDao.deleteNews(id);
		resp.sendRedirect("listAllNews.jsp");
		return true;
	}

	private void createNews(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String newsContent = (String) req.getParameter("news-content");
		News news = new News(new Text(newsContent));
		newsDao.insertNews(news);
		resp.sendRedirect("homepage.jsp");
	}
	
}
